package com.smfx.yxt.controller.sys.kccs;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.smfx.yxt.common.AdminUser;
import com.smfx.yxt.common.RspResult;
import com.smfx.yxt.common.enums.ExcelTemplate;
import com.smfx.yxt.common.enums.Status;
import com.smfx.yxt.controller.BaseController;
import com.smfx.yxt.excel.JxlsExcelView;
import com.smfx.yxt.model.ComboBox;
import com.smfx.yxt.model.CourseClassDate;
import com.smfx.yxt.model.Grid;
import com.smfx.yxt.model.KccsCourseInfo;
import com.smfx.yxt.model.TeacherInfo;
import com.smfx.yxt.page.OrderBy;
import com.smfx.yxt.page.Page;
import com.smfx.yxt.reqVo.KccsCourseQueryVO;
import com.smfx.yxt.service.IKccsCourseInfoService;
import com.smfx.yxt.service.ITeacherService;
import com.smfx.yxt.utils.CellUtil;
import com.smfx.yxt.utils.StringUtil;

@RequestMapping("sys/course/manage")
@Controller
public class SysCourseManageController extends BaseController {

	@Autowired
	private IKccsCourseInfoService kccsCourseInfoService;
	@Autowired
	private ITeacherService teacherService;
	
	@RequestMapping(value={"","/"})
	public String Index() {
		return "sys/kccs/courseManage";
	}
	
	@RequestMapping("pageQuery")
	@ResponseBody Object pageQuery(KccsCourseQueryVO vo){
		try {
			Page<KccsCourseInfo> page = new Page<>();
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			page.setParams(vo);
			List<OrderBy> orders = new ArrayList<>();
			orders.add(new OrderBy("IS_AGREE"));
			orders.add(new OrderBy("COURSE_TYPE"));
			orders.add(new OrderBy("COURSE_NO"));
			page.setSorts(orders);
			List<KccsCourseInfo> list = kccsCourseInfoService.selectListByPage(page);
			Grid grid = new Grid();
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping("addUpdate")
	@ResponseBody Object pageQuery(KccsCourseInfo record){
		try {
			AdminUser user = getAdminUser();
			record.setApprover(user.getTeacherInfo().getName());
			record.setUpdaterId(user.getTeacherInfo().getId());
			record.setUpdateTime(new Date());
			if (StringUtils.isNotBlank(record.getClassTeacherIds())) {
				List<TeacherInfo> list = teacherService.selectListByIds(Arrays.asList(record.getClassTeacherIds().split(",")));
				String teachers = "";
				String teacherIds = "";
				for(int i = 0; i < list.size(); i++) {
					TeacherInfo teacher = list.get(i);
					teachers += teacher.getName();
					teacherIds += teacher.getId();
					if((i+1) < list.size()){
						teachers += ",";
						teacherIds += ",";
					}
				}
				record.setClassTeacher(teachers);
				record.setClassTeacherIds(teacherIds);
			}
			kccsCourseInfoService.updateByPrimaryKeySelective(record);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("openClass")
	@ResponseBody Object openClass(String courseIds){
		try {
			AdminUser user = getAdminUser();
			List<String> list = Arrays.asList(courseIds.split(","));
			kccsCourseInfoService.updateBatchCourseStatus(list, 1, 
					user.getTeacherInfo().getId(), 
					user.getTeacherInfo().getName());
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("stopClass")
	@ResponseBody Object stopClass(String courseIds){
		try {
			AdminUser user = getAdminUser();
			List<String> list = Arrays.asList(courseIds.split(","));
			kccsCourseInfoService.updateBatchCourseStatus(list, 2, 
					user.getTeacherInfo().getId(), 
					user.getTeacherInfo().getName());
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("export")
	ModelAndView export(KccsCourseQueryVO vo) {
		ModelAndView modelAndView = new ModelAndView();
		try {
			vo.setIsAgree(1);
			Page<KccsCourseInfo> page = new Page<>();
			page.setPageNo(vo.getPage());
			page.setPageSize(Integer.MAX_VALUE - 1);
			page.setParams(vo);
			List<OrderBy> orders = new ArrayList<>();
			orders.add(new OrderBy("IS_AGREE"));
			orders.add(new OrderBy("COURSE_TYPE"));
			orders.add(new OrderBy("COURSE_NO"));
			orders.add(new OrderBy("ID"));
			page.setSorts(orders);
			List<KccsCourseInfo> list = kccsCourseInfoService.selectListByPage(page);
			CourseClassDate record = kccsCourseInfoService.selectCourseClassDate();
			modelAndView.getModelMap().addAttribute("list", list).
				addAttribute("classDate", record.getClassDate());
			
			JxlsExcelView view = new JxlsExcelView(ExcelTemplate.KCCS_COURSE);
			
			modelAndView.setView(view);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return modelAndView;
	}
	
	@RequestMapping("import")
	@ResponseBody Object courseImport(
			@RequestParam(value="files")MultipartFile buildInfo) {
		try {
			// 创建一个FileInputStream 文件输入流
	        InputStream inputStream = buildInfo.getInputStream();
	    	// 创建对Excel工作簿文件的引用
	        Workbook wookbook = null;
	        String filename = buildInfo.getOriginalFilename();
	        String fileType = filename.substring(filename.lastIndexOf(".") + 1,
	        		filename.length());
	        if (fileType.equals("xls")) {
	        	try{
	        		wookbook = new HSSFWorkbook(inputStream);
	        	}catch(Exception e){
	        		wookbook = null;
	           	 	wookbook = new XSSFWorkbook(inputStream);
	        	}
	        }else{
	       	 	wookbook = new XSSFWorkbook(inputStream);
	        }
	        // 在Excel文档中，第一张工作表的缺省索引是0
	        Sheet sheet = wookbook.getSheetAt(0);
	        int coloumNum=sheet.getRow(1).getPhysicalNumberOfCells();// 获取总列数
	        int rowNum=sheet.getPhysicalNumberOfRows();//获得总行数
	        if(rowNum <= 2) {
	        	return new RspResult(Status.TEMPLATE_DATA_NULL);
	        }
	        List<KccsCourseInfo> list = new ArrayList<>();
	        List<String> errorList = new ArrayList<>();
	        // 遍历行 从第三行开始遍历
	        for (int i = 2; i < rowNum; i++) {
	        	// 读取左上端单元格
	            Row row = sheet.getRow(i);
	            // 行不为空
	            if (row != null) {
	            	KccsCourseInfo plan = new KccsCourseInfo();
	            	for(int j = 0; j < coloumNum; j ++) {
	            		Cell cell = row.getCell((short)j);
	            		if(cell != null) {
	            			String val = CellUtil.getCellValue(cell);
	            			if(StringUtils.isBlank(val)) {
	            				errorList.add("第" + (i + 1) + "行第" + (j + 1) + "列的值为空");
	            				break;
	            			}
	            			if(j == 0) plan.setId(Integer.valueOf(val));
	            			else if(j == 1) plan.setCourseName(val);
	            			else if(j == 2) plan.setCourseSubject(val);
	            			else if(j == 3) plan.setCourseType(val);
	            			else if(j == 4) plan.setCourseNo(val);
	            			else if(j == 6) plan.setClassAddr(val);
	            			else if(j == 7) plan.setClassDate(val);
	            			else if(j == 8) plan.setLimitNum(Integer.valueOf(val));
	            			else if(j == 9) plan.setCourseDesc(val);
	            		}
	            	}
	            	list.add(plan);
	            }
	        }
	        if(!StringUtil.isNullOrEmpty(errorList)) {
	        	return new RspResult(Status.FAIL.getCode(), String.join(",", errorList));
	        }
	        kccsCourseInfoService.updateCourseType(list);
	        return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.TEMPLATE_ERROR);
	}
	
	@RequestMapping("classDate")
	@ResponseBody Object classDate(){
		CourseClassDate classDate = kccsCourseInfoService.selectCourseClassDate();
		String[] array = classDate.getClassDate().split(",");
		List<ComboBox> list = new ArrayList<>();
		for(String v : array) {
			list.add(new ComboBox(v, v));
		}
		return list;
	}
}
